package com.magic.uschat;

import org.greenrobot.eventbus.Subscribe;

import cn.bmob.newim.BmobIM;
import cn.bmob.newim.bean.BmobIMUserInfo;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.LogInListener;

import com.lidroid.xutils.view.annotation.ContentView;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;
import com.magic.uschat.bean.DbManager;
import com.magic.uschat.bean.User;
import com.magic.uschat.event.FinishEvent;
import com.magic.uschat.model.UserModel;

import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

@ContentView(R.layout.activity_login)
public class LoginActivity extends BaseActivity {

	@ViewInject(R.id.btn_login)
	private Button btn_login;
	@ViewInject(R.id.et_username)
	private EditText et_username;
	@ViewInject(R.id.et_passwd)
	private EditText et_passwd;
	@ViewInject(R.id.tv_register)
	private TextView tv_register;
	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
	}

	@OnClick(R.id.btn_login)
	public void onLoginClick(View v){
		UserModel.instance().login(et_username.getText().toString(), et_passwd.getText().toString(), new LogInListener<User>() {

			@Override
			public void done(User user, BmobException e) {
				if (e==null) {
					BmobIM.getInstance().updateUserInfo(new BmobIMUserInfo(user.getObjectId(),user.getUsername(), user.getAvatar()));
					DbManager.saveUser(user);
					UsChatApplication.instance().queryFriendList(user);
					startActivity(MainActivity.class, null,true);
				}else{
					toast(e.getMessage()+ "(" + e.getErrorCode() + ")");
				}
			}
			
		});
	}
	
	@OnClick(R.id.tv_register)
	public void onRegisterClick(View v){
		startActivity(RegisterActivity.class,null, false);
	}
	
	@Subscribe
    public void onEventMainThread(FinishEvent event){
        finish();
    }
	
}
